<template>
  <div>
    <el-card
      class="w-[70%] h-full"
      :style="{
        width: flowActiveIndex == 2 || flowActiveIndex == 4 ? '70%' : '100%',
      }"
    >
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              @click="handleClickBack"
              class="w-[2.5rem]"
              title="切换/返回"
            >
              <el-icon><Back /></el-icon>
            </el-button>
            <el-button
              type="danger"
              class="w-[3rem]"
              @click="handleClickEmpty"
              title="清空所选客户和检查单信息"
              >清空</el-button
            >
          </div>
          <div>
            <el-button
              type="primary"
              @click="handleOneClickSend"
              v-if="flowActiveIndex == 2"
            >
              一键下发
            </el-button>
            <el-button
              type="primary"
              @click="handleChangeDevice"
              v-if="flowActiveIndex == 2"
              >选择设备检查数据</el-button
            >
            <el-button
              type="primary"
              v-if="
                flowActiveIndex == 3 && tabName == 1 && opticianEditStatus == 1
              "
              @click="userStore.updateOpticianEditStatus(2)"
              >编辑</el-button
            >
            <el-button
              v-if="
                flowActiveIndex == 3 && tabName == 1 && opticianEditStatus == 2
              "
              @click="handleEditOptician(1)"
              >取消编辑</el-button
            >
            <el-button
              type="primary"
              v-if="
                flowActiveIndex == 3 && tabName == 1 && opticianEditStatus == 2
              "
              @click="handleEditOptician(2)"
              >保存</el-button
            >
          </div>
        </div>
      </template>

      <!-- 检查项 -->
      <check-the-entry v-if="flowActiveIndex == 2 && checkDetailForm.code" />

      <!-- 受检人信息 -->
      <flow-customer-info v-if="flowActiveIndex == 1 || flowActiveIndex == 2" />

      <!-- 区域数据 -->
      <el-scrollbar
        style="height: calc(100vh - 19.5rem)"
        class="mt-[0.3rem] pb-[0.4rem] pr-[0.4rem]"
        v-if="flowActiveIndex == 2 && checkDetailForm.code"
      >
        <RegionPage />
      </el-scrollbar>

      <!-- 方案 -->
      <SchemePage v-if="flowActiveIndex == 3" :checkId="checkDetailForm.id" />

      <!-- 报告 -->
      <ReportList v-if="flowActiveIndex == 5" />

      <!-- 销售 -->
      <InsertOrder v-if="flowActiveIndex == 4" />
    </el-card>

    <el-card
      class="analyse w-[29%] h-full"
      v-if="flowActiveIndex == 2 || flowActiveIndex == 4"
    >
      <template #header>
        <div
          class="w-full flex justify-between items-center pr-[1rem]"
          v-if="flowActiveIndex == 2"
        >
          <el-tag type="primary">数据分析</el-tag>
          <CopyButton text="1" title="复制" v-if="checkDetailForm.code" />
        </div>
        <el-tag v-if="flowActiveIndex == 4">历史销售单</el-tag>
      </template>
      <DataAnalyse v-if="flowActiveIndex == 2 && checkDetailForm.code" />
      <el-empty :image-size="140" description="暂未选择检查单号"></el-empty>
      <div v-if="flowActiveIndex == 4">
        <SalesTicket />
      </div>
    </el-card>

    <!-- 选择设备检查数据 -->
    <el-drawer
      v-model="device_drawer"
      size="80%"
      title="选择设备检查数据"
      destroy-on-close
    >
      <ChangeDeviceCheckData
        :outCodeList="outCodeList"
        @handleBack="handleDeviceBack"
      />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import ChangeDeviceCheckData from "@/components/ChangeDeviceCheckData.vue";
import CheckTheEntry from "@/components/CheckTheEntry.vue";
import FlowCustomerInfo from "@/components/Flow/FlowCustomerInfo.vue";
import RegionPage from "./Region/index.vue";
import CopyButton from "@/components/CopyButton.vue";
import DataAnalyse from "./DataAnalyse.vue";
import SchemePage from "./SchemePage/index.vue";
import InsertOrder from "../../OrderList/component/HeaderInsertOrder.vue";
import ReportList from "./ReportList/index.vue";
import SalesTicket from "./SalesTicket.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  SendMessageToDevices,
  QueryRegion,
} from "../../../../../wailsjs/go/api/ReportApi.js";

import {
  ConnectToSSE,
  StopSSE,
} from "../../../../../wailsjs/go/api/CustomerApi.js";

onMounted(() => {});

const userStore = useUserStore();
const {
  cutStatus,
  flowActiveIndex,
  checkDetailForm,
  tabName,
  opticianEditStatus,
} = storeToRefs(userStore);

// 返回
const handleClickBack = () => {
  userStore.updateCutStatus(1);
};
// 清空
const handleClickEmpty = () => {
  ElMessageBox.confirm("你确定要清空数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    userStore.updateCheckDetailForm({});
    userStore.updateFlowActiveIndex(1);
  });
};

// 一键下发
const handleOneClickSend = () => {
  if (!checkDetailForm.value.code) return ElMessage.error("请先选择检查单号");

  ElMessageBox.confirm("你确定要下发数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let projectIds = checkDetailForm.value.projectList.map((item) => item.id);

    handleApiResponse(() =>
      SendMessageToDevices({
        projectIdList: projectIds,
        scan: `{type=inspect&&listId=${checkDetailForm.value.id}&&birthday=${checkDetailForm.value.birthday}&&archivesCode=${checkDetailForm.value.medicalCardNumber}&&code=${checkDetailForm.value.code}&&name=${checkDetailForm.value.relationName}&&phone=${checkDetailForm.value.phone}&&sex=${checkDetailForm.value.sex}&&age=${checkDetailForm.value.age}}`,
      })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success("下发成功");
      }
    });
  });
};

// 选择设备检查数据
const device_drawer = ref(false);
const outCodeList = ref([]); // 设备编码/外码
const handleChangeDevice = () => {
  if (!checkDetailForm.value.code) return ElMessage.error("请先选择检查单号");

  outCodeList.value = [];
  let list = [];
  checkDetailForm.value.projectList.forEach((item) => {
    item.deviceList.forEach((item2) => {
      if (item2.isAuthentic == 1) {
        list.push({ ...item2, projectId: item.id });
      }
    });
  });

  outCodeList.value = list.filter(
    (item, index, self) =>
      index === self.findIndex((t) => t.deviceSn === item.deviceSn)
  );

  device_drawer.value = true;
};
const handleDeviceBack = (val) => {
  if (val && val == 1) {
    getRegionList();
  }
  device_drawer.value = false;
};

// 取消编辑/提交 方案-配镜
// type: 1.取消 2.提交
const handleEditOptician = (type) => {
  // 708686;

  setStorageWithEvent("refresh_optician", {
    opticianType: type,
  });
};

// ------------------------获取区域数据点 start------------------------
const regionData = ref([]);

let customerInfo = ref(""); // 生成ai需要的信息

// 1:视力
const vision_data = ref({}); // 视力
const vision_projectId = ref(null); // 视力项目id

// 2:电脑验光
const computer_optometry_data = ref({}); // 电脑验光
const computer_optometry_projectId = ref(null); // 电脑验光项目id

// 3:眼压
const iop_data = ref({}); // 眼压
const iop_projectId = ref(null); // 眼压项目id

// 4.生物测量 aop
const od_os_data = ref({}); // OD / 右眼 ，  OS / 左眼
const od_os_projectId = ref(null); // OD / 右眼 ，  OS / 左眼项目id

// 5.主观验光
const subjectivity_data = ref({}); // 主观验光
const subjectivity_projectId = ref(null); // 主观验光项目id

// 7.配镜参数
const optometrist_query_data = ref({}); // 配镜参数
const optometrist_query_projectId = ref(null); // 配镜参数项目id

// 8.视功能(牛眼)
const visual_function_niu_data = ref({}); // 视功能(牛眼)
const visual_function_niu_projectId = ref(null); // 视功能(牛眼)项目id

async function getRegionList(type) {
  let projectIds =
    checkDetailForm.value.projectList.map((item) => item.id) || [];

  handleApiResponse(() =>
    QueryRegion({
      checklistId: checkDetailForm.value.id,
      projectIds: projectIds,
    })
  ).then((res) => {
    handleEmptyRegionData();
    if (res.code == 0) {
      // ElMessage.success("获取区域数据成功");
      console.log("获取区域数据成功", res.data);

      if (type == 1) ElMessage.success("更新数据成功");

      regionData.value =
        res.data?.regionInfos.map((item) => {
          return {
            regionId: item.regionId,
            regionName: item.regionName,
            projectId: item.projectId,
            regionResult: JSON.parse(item.regionResult || "[]"),
          };
        }) || [];

      checkDetailForm.value.regionData = regionData.value.sort(
        (a, b) => a.regionId - b.regionId
      );

      // regionData.value.forEach((item) => {
      //   checkDetailForm.value.projectList.forEach((item2) => {
      //     if (item.projectId == item2.id) {
      //       item2.regionId = item.regionId;
      //       item2.regionName = item.regionName;
      //     }
      //   });
      // });

      setStorageWithEvent("refresh_region_item_2");

      regionData.value.forEach((item) => {
        if (item.regionId == 1) {
          // 视力
          item.regionResult.forEach((item) => {
            vision_data.value[item.datapointTypeValue] = item.value || "";
          });
          vision_projectId.value = item.projectId;
        } else if (item.regionId == 2) {
          // 电脑验光
          item.regionResult.forEach((item) => {
            computer_optometry_data.value[item.datapointTypeValue] =
              item.value || "";
          });
          computer_optometry_projectId.value = item.projectId;
        } else if (item.regionId == 3) {
          // 眼压
          item.regionResult.forEach((item) => {
            iop_data.value[item.datapointTypeValue] = item.value || "";
          });
          iop_projectId.value = item.projectId;
        } else if (item.regionId == 4) {
          // OD / 右眼 ，   OS / 左眼
          item.regionResult.forEach((item) => {
            od_os_data.value[item.datapointTypeValue] = item.value || "";
          });
          od_os_projectId.value = item.projectId;
        } else if (item.regionId == 5) {
          // 主观验光
          item.regionResult.forEach((item) => {
            subjectivity_data.value[item.datapointTypeValue] = item.value || "";
          });
          subjectivity_projectId.value = item.projectId;
        } else if (item.regionId == 7) {
          // 配镜参数
          item.regionResult.forEach((item) => {
            optometrist_query_data.value[item.datapointTypeValue] =
              item.value || "";
          });
          optometrist_query_projectId.value = item.projectId;
        } else if (item.regionId == 8) {
          // 视功能(牛眼)
          item.regionResult.forEach((item) => {
            visual_function_niu_data.value[item.datapointTypeValue] =
              item.value || "";
          });
          visual_function_niu_projectId.value = item.projectId;
        }
      });

      regionData.value.forEach((item) => {
        if (item.regionResult && item.regionResult.length > 0) {
          item.regionResult.forEach((e) => {
            if (customerInfo.value == "") {
              customerInfo.value =
                e.mark + e.datapointTypeTitle + ":" + (e.value || "---");
            } else {
              customerInfo.value +=
                "," + e.mark + e.datapointTypeTitle + ":" + (e.value || "---");
            }
          });
        }
      });

      setStorageWithEvent("refresh_region_data", {
        customerInfo: `姓名:${checkDetailForm.value.relationName},年龄:${
          checkDetailForm.value.age
        }岁,性别:${
          checkDetailForm.value.sex == 1
            ? "男"
            : checkDetailForm.value.sex == 2
            ? "女"
            : "未知"
        },职业:${checkDetailForm.value.occupation},工作环境:${
          checkDetailForm.value.workEnvironment
        },用眼距离:${checkDetailForm.value.eyeDistance},${customerInfo.value}`,
        aiid: res.data.aiid || "",
        aiResult: res.data.aiResult || "",
        editResult: res.data.editResult || "",
        regionData: regionData.value, // 区域所有数据点
        vision_data: vision_data.value, // 1.视力
        vision_projectId: vision_projectId.value,
        computer_optometry_data: computer_optometry_data.value, // 2.电脑验光
        computer_optometry_projectId: computer_optometry_projectId.value,
        iop_data: iop_data.value, // 3.眼压
        iop_projectId: iop_projectId.value,
        od_os_data: od_os_data.value, // 4.生物测量
        od_os_projectId: od_os_projectId.value,
        subjectivity_data: subjectivity_data.value, // 5.主观验光
        subjectivity_projectId: subjectivity_projectId.value,
        optometrist_query_data: optometrist_query_data.value, // 7.配镜参数
        optometrist_query_projectId: optometrist_query_projectId.value,
        visual_function_niu_data: visual_function_niu_data.value, // 8.视功能(牛眼)
        visual_function_niu_projectId: visual_function_niu_projectId.value,
      });
    }
  });
}

// 清空区域数据点
const handleEmptyRegionData = () => {
  vision_data.value = {}; // 1.视力
  vision_projectId.value = null;
  computer_optometry_data.value = {}; // 2.电脑验光
  computer_optometry_projectId.value = null;
  iop_data.value = {}; // 3.眼压
  iop_projectId.value = null;
  od_os_data.value = {}; // 4.生物测量
  od_os_projectId.value = null;
  subjectivity_data.value = {}; // 5.主观验光
  subjectivity_projectId.value = null;
  optometrist_query_data.value = {}; // 7.配镜参数
  optometrist_query_projectId.value = null;
  visual_function_niu_data.value = {}; // 8.视功能(牛眼)
  visual_function_niu_projectId.value = null;
};
// ------------------------获取区域数据点 end------------------------



watchEffect(() => {
  if (
    flowActiveIndex.value == 2 &&
    checkDetailForm.value.code &&
    checkDetailForm.value.id
  ) {
    getRegionList();
  }
});

// 点击检查项更新数据点信息
let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_data", (e) => {
    getRegionList();
  });
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});
</script>

<style scoped lang="scss">
.analyse :deep(.el-card__body) {
  padding-top: 0rem !important;
}
</style>